<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import Banner from "@/components/MyComponents/Banner.vue";
import CreateFamilyDialog from "@/components/MyComponents/CreateFamilyDialog.vue";
import {
  getFamilyUserInfo,
  addFamilyUserInfo,
  checkAddFamilyUser,
  getFamilyAndContractInfo
} from "@/api/familyManagement/docFamily";

// 设置导航标题
const bannerTitle = ref("家庭详情");

// 家庭基本信息（接口现在返回的是数组）
const familyList = ref<any[]>([]);
// 家庭成员
const familyMembers = ref<any[]>([]);

// 创建/修改家庭弹窗控制
const showCreateDialog = ref(false);
// 模式标识：create / edit
const dialogMode = ref<"create" | "edit">("create");

// 添加成员弹窗控制
const showAddMemberDialog = ref(false);
const addMemberForm = ref({ userName: "" });

// 搜索处理函数
const handleBannerSearch = (keyword: string) => {
  console.log("搜索关键词:", keyword);
};

// 加载家庭详情和成员
const loadFamilyInfo = async () => {
  try {
    // 获取家庭信息和签约信息
    const res = await getFamilyAndContractInfo();
    console.log("获取家庭信息成功", res);
    if (res.code === 200 && res.data) {
      familyList.value = res.data;
      // 获取家庭成员信息
      const memberRes = await getFamilyUserInfo();
      familyMembers.value = memberRes.code === 200 ? memberRes.data : [];
    } else {
      familyList.value = [];
      familyMembers.value = [];
    }
  } catch (e) {
    console.error("加载家庭信息失败", e);
    familyList.value = [];
    familyMembers.value = [];
  }
};

// 点击创建家庭显示弹窗
const handleCreateFamily = () => {
  dialogMode.value = "create";
  showCreateDialog.value = true;
};

// 点击修改家庭显示弹窗
const handleEditFamily = () => {
  dialogMode.value = "edit";
  showCreateDialog.value = true;
};

// 点击添加成员显示弹窗
const handleAddMember = () => {
  addMemberForm.value.userName = "";
  showAddMemberDialog.value = true;
};

// 确认添加成员
const handleConfirmAddMember = async () => {
  if (!addMemberForm.value.userName) {
    return ElMessage.warning("请输入成员账号");
  }

  try {
    // 调用后台接口进行添加成员前的校验
    const res = await checkAddFamilyUser(addMemberForm.value.userName);

    // 根据后台返回的操作结果判断要显示的提示
    const result = res.data;

    switch (result) {
      case "CHECK_FAMILY_USER_NUM":
        ElMessage.warning("家庭成员已满");
        break;
      case "CHECK_IS_EXIST":
        ElMessage.warning("该用户不存在");
        break;
      case "CHECK_IS_DOCTOR":
        ElMessage.warning("不能添加医生");
        break;
      case "CHECK_IS_TEAM":
        ElMessage.warning("该用户已有团队");
        break;
      case "CHECK_IS_SELF":
        ElMessage.warning("不能添加自己");
        break;
      default:
        await addFamilyUserInfo(addMemberForm.value.userName);
        ElMessage.success("添加成员成功");
        showAddMemberDialog.value = false;
        await loadFamilyInfo();
        break;
    }
  } catch (e) {
    console.error("添加成员失败", e);
    ElMessage.error("添加成员失败，请检查账号");
  }
};

// 弹窗关闭后刷新家庭信息
const handleDialogReload = () => {
  loadFamilyInfo();
};

onMounted(() => {
  loadFamilyInfo();
});
</script>

<template>
  <div class="family-details-page">
    <Banner :title="bannerTitle" @search="handleBannerSearch" />

    <div class="content-container">
      <!-- 家庭基本信息卡片 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header" style="display:flex; justify-content:space-between; align-items:center;">
            <span>家庭基本信息</span>
            <div>
              <el-button
                  v-if="!familyList.length"
                  type="primary"
                  size="small"
                  @click="handleCreateFamily"
              >
                创建家庭
              </el-button>
              <el-button
                  v-else
                  type="primary"
                  size="small"
                  @click="handleEditFamily"
              >
                修改信息
              </el-button>
            </div>
          </div>
        </template>

        <div v-if="familyList.length > 0" class="info-content">
          <!-- 基础家庭信息 -->
          <el-row :gutter="20" class="base-info">
            <el-col :span="12">
              <div class="info-item">
                <span class="label">家庭名称：</span>
                <span class="value">{{ familyList[0].familyName || "暂无家庭名称" }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">家庭地址：</span>
                <span class="value">{{ familyList[0].familyAddress || "暂无地址" }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">家庭成员数：</span>
                <span class="value">{{ familyList[0].familyUserNum || 1 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">已签约团队数：</span>
                <!-- 判断是否有签约团队，若无，显示为 0 -->
                <span class="value">
                  {{ familyList[0].contractState ? familyList.length : 0 }}
                </span>
              </div>
            </el-col>
          </el-row>

          <!-- 签约团队信息 -->
          <div class="contracts">
            <h4 class="contracts-title">签约团队信息</h4>
            <el-row :gutter="20">
              <el-col :span="12" v-for="(team, index) in familyList" :key="index">
                <el-card class="contract-card" shadow="hover">
                  <div class="info-item">
                    <span class="label">团队名称：</span>
                    <span class="value">{{ team.teamName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">签约开始日期：</span>
                    <span class="value">{{ team.contractStartDate || "无" }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">签约结束日期：</span>
                    <span class="value">{{ team.contractEndDate || "无" }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">合同状态：</span>
                    <span
                        class="value"
                        :class="team.contractState === '1' ? 'status-active' : 'status-inactive'"
                    >
                      {{ team.contractState === '1' ? "已签约" : "未生效" }}
                    </span>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </div>

        <div v-else class="empty-info">
          <span>暂无家庭信息</span>
        </div>
      </el-card>

      <!-- 家庭成员列表 -->
      <el-card class="members-card">
        <template #header>
          <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
            <span>家庭成员列表</span>
            <el-button type="primary" size="small" @click="handleAddMember">添加成员</el-button>
          </div>
        </template>

        <div v-if="familyMembers.length > 0">
          <el-table :data="familyMembers" style="width: 100%" border>
            <el-table-column prop="userName" label="账号" width="150" />
            <el-table-column prop="nickName" label="昵称" width="150" />
            <el-table-column prop="email" label="邮箱" width="200" />
            <el-table-column prop="phonenumber" label="手机" width="150" />
            <el-table-column prop="userAge" label="年龄" width="80" />
          </el-table>
        </div>

        <div v-else class="empty-members">
          暂无家庭成员
        </div>
      </el-card>
    </div>

    <!-- 创建/修改家庭弹窗 -->
    <CreateFamilyDialog
        :visible="showCreateDialog"
        :mode="dialogMode"
        :familyInfo="familyList[0] || null"
        @close="showCreateDialog = false"
        @reload="handleDialogReload"
    />

    <!-- 添加成员弹窗 -->
    <el-dialog title="添加家庭成员" v-model="showAddMemberDialog" width="400px">
      <el-form :model="addMemberForm" label-width="80px">
        <el-form-item label="成员账号">
          <el-input v-model="addMemberForm.userName" placeholder="请输入成员账号" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddMemberDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmAddMember">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.family-details-page {
  padding: 20px;
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card,
.members-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .card-header {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
  }
}

.info-content {
  padding: 20px;

  .base-info {
    margin-bottom: 20px;
  }
}

.info-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;

  .label {
    width: 120px;
    font-weight: bold;
    color: #606266;
  }

  .value {
    color: #303133;

    &.status-active {
      color: #67c23a;
      font-weight: bold;
    }

    &.status-inactive {
      color: #f56c6c;
      font-weight: bold;
    }
  }
}

.contracts {
  margin-top: 10px;

  .contracts-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 12px;
  }

  .contract-card {
    margin-bottom: 16px;
  }
}

.empty-info,
.empty-members {
  padding: 20px;
  color: #909399;
  font-size: 14px;
}
</style>
